package com.kancy.swing.framework;

import com.kancy.swing.log.Log;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Swing
 *
 * @author kancy
 * @date 2020/2/16 5:07
 */
public class Swing {

    /**
     * 窗口关闭监听
     */
    private static final WindowAdapter WINDOW_EXIT_ON_CLOSE_ADAPTER = new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {
            System.exit(0);
        }
    };

    /**
     * Frame默认设置
     * @param frame
     */
    public static void setDefaultFrameStyle(Frame frame){
        frame.addWindowListener(WINDOW_EXIT_ON_CLOSE_ADAPTER);
        frame.setAlwaysOnTop(true);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    /**
     * 设置随机的LookAndFeel
     */
    public static void setRandomLookAndFeel() {
        // 只随机比较好看的LookAndFeel
        String[] lookAndFeels = new String[]{
                "javax.swing.plaf.metal.MetalLookAndFeel",
                "javax.swing.plaf.nimbus.NimbusLookAndFeel",
                "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
        };
        setLookAndFeel(lookAndFeels[ThreadLocalRandom.current().nextInt(0, lookAndFeels.length)]);
    }

    /**
     * 设置 LookAndFeel
     * @param lookAndFeelClassName
     */
    public static void setLookAndFeel(String lookAndFeelClassName) {
        try {
            UIManager.setLookAndFeel(lookAndFeelClassName);
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }

    /**
     * 设置默认Ui字体
     */
    public static void setUIFont() {
        Font font = new Font("宋体", Font.PLAIN, 12);
        setUIFont(font);
    }

    /**
     * 设置Ui字体
     * @param font
     */
    public static void setUIFont(Font font) {
        FontUIResource f = new FontUIResource(font);
        Enumeration<?> keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource){
                UIManager.put(key, f);
            }
        }
    }

    public static void setUIManager(){
        UIManager.put("OptionPane.titleText", "确认对话框");
        UIManager.put("OptionPane.yesButtonText", "好了");
        UIManager.put("OptionPane.noButtonText", "不行");
        UIManager.put("OptionPane.cancelButtonText", "关闭");
    }
}
